# https://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=cname
import urllib.request
import urllib.parse


def create_request(page1):
    # 基础请求地址
    base_url = 'https://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=cname'
    # 请求参数
    data = {
        "cname": "上海",
        "pid": "",
        "pageIndex": page1,
        "pageSize": 10,
    }
    # 请求 参数编码
    data = urllib.parse.urlencode(data).encode('utf-8')
    url = base_url
    # UA 信息
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                      'Chrome/123.0.0.0 Safari/537.36'
    }
    # 定制请求对象
    return urllib.request.Request(url, data, headers=headers)


def get_content(request1):
    response = urllib.request.urlopen(request1)
    return response.read().decode('utf-8')


def down_load(page, content):
    with open('kfc' + str(page) + '.json', 'w', encoding="utf-8") as f:
        f.write(content)


if __name__ == '__main__':
    start_page = int(input('请输入起始页:'))
    end_page = int(input('请输入结束页:'))

    for page in range(start_page, end_page + 1):
        # 请求对象的定制
        request = create_request(page)
        content = get_content(request)
        down_load(page, content)

